/************************************************************
 * Project Name		[Thinking_In_Java]
 * File Name     	[pkg_05_swing.Example_05_Image.java]
 * Creation Date 	[21-Jun-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_05_swing;

import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * 图片
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Example_05_Image {
	/**
	 * 测试方法
	 * 
	 * @param args
	 *            命令行参数
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				ImageFrame frame = new ImageFrame();
				frame.setVisible(true);
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.setResizable(false);
			}
		});
	}
}

/**
 * 显示图片的窗体
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 */
class ImageFrame extends JFrame {

	private static final long serialVersionUID = 3578904098731094710L;

	public ImageFrame() {
		setTitle("Image reading");
		this.setSize(420, 635);
		setLocationByPlatform(true);
		getContentPane().add(new ImagePanel());
	}
}

/**
 * 显示图片的面板
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 */
class ImagePanel extends JPanel {

	private static final long serialVersionUID = 5323313684369782714L;

	private Image image = null;

	public ImagePanel() {
		try {
			/*
			 * 如果在加载图片时出现 Can't load standard profile: GRAY.pf<br>
			 * 请检查JDK安装路径下的如下目录: jdk1.6.0_05\jre\lib\cmm, 看里面是否缺少文件
			 */
			// 方法1
			image = Toolkit.getDefaultToolkit().getImage(
					ImageFrame.class.getClassLoader().getResource(
							"pkg_resources/pic_01.jpg"));
			// 方法2
			image = ImageIO.read(new java.io.File(
					"src_01_language_basic/pkg_resources/pic_01.jpg"));
			// 方法3
			image = ImageIO.read(ImageFrame.class.getClassLoader().getResource(
					"pkg_resources/pic_01.jpg"));
			// 方法4
			image = new ImageIcon(
					"src_01_language_basic/pkg_resources/pic_01.jpg")
					.getImage();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void paintComponent(Graphics g) {
		if (image == null) {
			return;
		}
		g.drawImage(image, 0, 0, this);

		// int imageWidth = image.getWidth(this);
		// int imageHeight = image.getHeight(this);
		//
		// for (int i = 0; i * imageWidth < this.getWidth(); i++) {
		// for (int j = 0; j * imageHeight < this.getHeight(); j++) {
		// if (i + j > 0) {
		// // 拷贝屏幕的一片区域
		// g.copyArea(0, 0, imageWidth, imageHeight, i * imageWidth, i
		// * imageHeight);
		// }
		// }
		// }
	}
}
